package com.bw.lib_storage.db

import android.content.ContentValues.TAG
import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.bw.lib_storage.db.entity.History
import com.bw.lib_storage.db.entity.Student
import net.sqlcipher.database.SupportFactory

/**
 * @author ykj
 * @date 2025-09-15 16:52
 * @description
 * 初始化数据库
 */
object DBUtils {
    private lateinit var db:AppDataBase

    /**
     * 初始化数据库
     */
    fun init(context:Context,dbName:String){
        //版本升级1_2:新增字段
        val MIGRATION_1_2 = object : Migration(1,2){
            override fun migrate(db: SupportSQLiteDatabase) {
                db.execSQL("ALTER TABLE history ADD COLUMN query_time INTEGER NOT NULL DEFAULT 0")
            }

        }
        val MIGRATION_2_3 = object : Migration(2,3){
            //版本升级2_3:新增表
            override fun migrate(db: SupportSQLiteDatabase) {
                //初始化数据库
                db.execSQL("ALTER TABLE student ADD COLUMN query_time INTEGER NOT NULL DEFAULT 0")
            }

        }
        db = Room.databaseBuilder(context,AppDataBase::class.java,dbName)
            .allowMainThreadQueries() //不规范的，协程线程访问数据库，耗时操作
            .openHelperFactory(SupportFactory("123456".toByteArray())) //数据库加密
            .addMigrations(MIGRATION_1_2) //添加升级1-2
//            .addMigrations(MIGRATION_2_3) //添加升级2-3
            .build()
    }

    /**
     * 获得数据库
     */
    fun getDB():AppDataBase{
        if (db == null){
            throw NullPointerException("请先初始化数据库")
        }
        return db
    }


}